package com.bsoft.gol.hcs.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author tongtp
 * @version v0.1
 * @description IP工具类
 * @create 2019-05-15 13:31
 **/
public class IPUtil {

    private final static Logger log = LoggerFactory.getLogger(IPUtil.class);


    /**
     * @param
     * @throws
     * @description: 获取本机所有IP
     * @return: java.util.List<java.lang.String>
     * @author: tongtp
     * @date: 2019/5/15 13:32
     */
    public static List<String> getLocalIPList() {
        List<String> ipList = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        log.info("IPList={}", ipList);
        return ipList;
    }

    /**
     * @param IP
     * @throws
     * @description: 检查IP是否在本地IP列表中
     * @return: boolean
     * @author: tongtp
     * @date: 2019/5/15 13:37
     */
    public static boolean cheakIPInLocalIPList(String IP) {
        List<String> localIPList = getLocalIPList();
        for (String localIP :
                localIPList) {
            if (localIP.equals(IP)) {
                return true;
            }
        }
        return false;
    }

}
